package com.bilin.coin.common.base;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.LocaleList;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.arouter.utils.TextUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.AppManager;
import com.bilin.coin.R;
import com.bilin.coin.bean.UserInfo;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.SharedPreferencesUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Locale;

import butterknife.ButterKnife;


/**
 * Activity的基础类
 */

public abstract class BaseAppCompatActivity extends RxAppCompatActivity {


    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 加载布局文件
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 头部布局文件
     */
    public LinearLayout parentLinearLayout;
    protected TextView mTvTitle;
    //public Toolbar mToolbar;

    public TextView getmTvTitle() {
        return mTvTitle;
    }

    protected ImageView mIvMenu;
    protected ImageView iv_back;
    protected Toast mToast;
    TextView mTvMenu;

    public void setmTvTitle(TextView mTvTitle) {
        this.mTvTitle = mTvTitle;
    }

    public TextView getmTvMenu() {
        return mTvMenu;
    }


    /**
     * 判断是否加载头部布局，true为加载，false反之。
     */
    protected boolean mShowToolBar = true;
    protected boolean mShowBack = true;
    protected boolean mLanguage = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getInstance().addActivity(this);
        //跟随系统变化语言
       /* if (!SharedPreferencesUtils.getInstance().getString("language", "").equals("")) {
            languageSetting(com.gdwjkj.auction.utils.SharedPreferencesUtils.getInstance().getString("language", ""));
        }*/
        //setEnableNightMode((Boolean) SharedPreferencesUtils.getInstance().getData(ApiConstant.IsSwitchNight,false));


        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //路由获取数据
        ARouter.getInstance().inject(this);
        //沉浸式状态栏
        if (isSetStatusBarColor()) {
            //StatusBarUtil.setColor(BaseAppCompatActivity.this, getResources().getColor(R.color.mainColorBg), 0);
//            ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).init();
        }


        //StatusBarUtil.setTransparent(this);
        if (isShowToolBar()) {
            initHeadView(R.layout.public_toolbar);
            mTvTitle = findViewById(R.id.tv_title);
            //mToolbar = findViewById(R.id.toolbar);
            mIvMenu = findViewById(R.id.iv_menu);
            mTvMenu = findViewById(R.id.tv_menu);
            iv_back = findViewById(R.id.iv_back);
            MenuOnClickListener();
        }

        if (isShowToolBar() && isShowBack()) {
            //mToolbar.setNavigationIcon(R.drawable.ic_chevron_left_black_24dp);
            finishActivity();
        }
        if (getLayoutId() > 0)
            setContentView(getLayoutId());
        //注解绑定
        ButterKnife.bind(this);
        //初始化沉浸式
        //initImmersionBar();
        initData();
        initView();


    }

    protected boolean isSetStatusBarColor() {
        return true;
    }

    /**
     * 初始化沉浸式
     * Init immersion bar.
     */
    protected void initImmersionBar() {
        //设置共同沉浸式样式
        //ImmersionBar.with(this).navigationBarColor(R.color.colorPrimary).init();
        ImmersionBar.with(this).titleBar(R.id.toolbar).init();
    }


    public void setDefaultTheme(boolean isNight) {
        AppCompatDelegate.setDefaultNightMode(isNight ?
                AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
    }

    public void setEnableNightMode(boolean isNight) {
        //boolean isNight = (boolean) SharedPreferencesUtils.getInstance().getData(ApiConstant.IsSwitchNight, false);
        if (isNight) {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
        //recreate();
    }
    /*
     *//**
     * 第一次启动的时候设置语言
     * @param
     *//*
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(ContextWrapperUtils.wrap(newBase, SharedPreferencesUtils.getInstance().getString("language", "")));
    }*/


    /**
     * 设置头部布局
     *
     * @param layoutResID
     */
    public void initHeadView(@LayoutRes int layoutResID) {
        ViewGroup viewGroup = findViewById(android.R.id.content);
        if (viewGroup != null) {
            viewGroup.removeAllViews();
        }
        parentLinearLayout = new LinearLayout(this);
        parentLinearLayout.setOrientation(LinearLayout.VERTICAL);
        viewGroup.addView(parentLinearLayout);
        LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true);
    }

    /**
     * 加载内容布局
     *
     * @param layoutResID
     */
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        if (isShowToolBar()) {
            LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true);
        } else {
            super.setContentView(layoutResID);
        }
    }

    /**
     * 隐藏键盘
     */
    public void hideSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            View localView = getCurrentFocus();
            if (localView != null && localView.getWindowToken() != null) {
                IBinder windowToken = localView.getWindowToken();
                inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
            }
        }
    }

    /**
     * 显示键盘
     */
    public void showSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            View localView = getCurrentFocus();
            if (localView != null && localView.getWindowToken() != null) {
                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 子类重新该方法可以改变是否显示状态栏
     *
     * @param
     */
    public boolean isShowToolBar() {
        return mShowToolBar;
    }

    public boolean isShowBack() {
        return mShowBack;
    }

    /**
     * 注册关闭页面事件
     */
    public void finishActivity() {
        if (iv_back != null) {
            iv_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    back();
                    finish();
                }
            });
            mTvTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    back();
                    finish();
                }
            });
        }
    }

    public void back() {

    }

    public void MenuOnClickListener() {
        if (mIvMenu != null) {
            mIvMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setMenuOnClickListener();
                }
            });
        }
        if (mTvMenu != null) {
            mTvMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setMenuOnClickListener();
                }
            });
        }
    }

    /**
     * 子类重写该方法实现点击回调
     */
    public void setMenuOnClickListener() {

    }

    public void setMenu(CharSequence menuName) {
        mIvMenu.setVisibility(View.GONE);
        mTvMenu.setVisibility(View.VISIBLE);
        mTvMenu.setText(menuName);
    }

    public void setMenu(Drawable drawable) {
        mIvMenu.setVisibility(View.VISIBLE);
        mTvMenu.setVisibility(View.GONE);
        mIvMenu.setImageDrawable(drawable);
    }

    public void setMenu(int resId) {
        mIvMenu.setVisibility(View.VISIBLE);
        mTvMenu.setVisibility(View.GONE);
        mIvMenu.setImageResource(resId);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(CharSequence title) {
        if (mTvTitle != null) {
            mTvTitle.setText(title);
        }

    }


    /**
     * 提示框
     *
     * @param text
     */
    public void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 经典无参跳转
     *
     * @param path
     */
    public void baseStartActivity(String path) {
        ARouter.getInstance().build(path).navigation(this);
    }

    /**
     * 有参跳转
     *
     * @param path
     * @return
     */
    public Postcard baseStartActivityWith(String path) {
        return ARouter.getInstance().build(path);
    }

    /**
     * 带回调的跳转
     *
     * @param path
     * @param RequestCode
     */
    public void baseStartActivityForResult(String path, int RequestCode) {
        ARouter.getInstance().build(path).navigation(this, RequestCode);
    }


    /**
     * 设置语言
     *
     * @param language
     */
    public void languageSetting(String language) {
        // 本地语言设置
        /*Locale myLocale = new Locale(language);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);*/
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        Locale locale = Locale.CHINESE;
        String lang = SharedPreferencesUtils.getInstance().getString("language", "");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(Locale.CHINESE);
            if (lang.equals("zh_rTW")) {
                localeList = new LocaleList(Locale.TAIWAN);
            } else if (lang.equals("en")) {
                localeList = new LocaleList(Locale.ENGLISH);
            } else if (lang.equals("ko-rKR")) {
                localeList = new LocaleList(Locale.KOREA);
            } else {

            }
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);
            createConfigurationContext(config);
            Locale.setDefault(locale);
        } else {
            if (lang.equals("zh_rTW")) {
                config.locale = Locale.TAIWAN;
            } else if (lang.equals("en")) {
                config.locale = Locale.ENGLISH;
            } else if (lang.equals("ko-rKR")) {
                config.locale = Locale.KOREA;
            } else {
                config.locale = locale;
            }
        }
        resources.updateConfiguration(config, dm);

    }


    @Override
    public void onStop() {
        super.onStop();
    }


    /***
     * 网络请求后显示服务器返回的信息
     */
    public void showMsg(Throwable e) {
        DialogUtils.dismissDialogLoading();
        Throwable cause = e.getCause();
        if (cause != null) {
            if (!TextUtils.isEmpty(cause.getMessage())) {
                showToast(cause.getMessage());
            } else {
                showToast("网络超时...");
            }
        }
    }

    public void copeClipSuccess(TextView textView) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        //cm.setText(textView.getText().toString());
        ClipData clipData = ClipData.newPlainText("copy data", textView.getText());
        cm.setPrimaryClip(clipData);
        showToast("复制成功");
    }

    protected void copeClipSuccess(String str) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        //cm.setText(textView.getText().toString());
        ClipData clipData = ClipData.newPlainText("copy data", str);
        cm.setPrimaryClip(clipData);
        showToast("复制成功");
    }

    protected void pasteClipSuccess(TextView textView) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm.hasPrimaryClip()
                && cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            ClipData.Item item = cm.getPrimaryClip().getItemAt(0);
            CharSequence text = item.getText();
            if (text == null) {
                showToast("粘贴成功");
                return;
            }
            textView.setText(text);
        }
    }

    protected boolean isExistOnClip() {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm.hasPrimaryClip()
                && cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            ClipData.Item item = cm.getPrimaryClip().getItemAt(0);
            CharSequence text = item.getText();
            if (text == null) {
                return false;
            }
            if (text.toString().contains(ApiConstant.CLIP_KEY_STR)) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        this.getWindow().setAttributes(lp);
    }

    /**
     * 获取用户信息
     */
    /**
     * 获取用户信息
     */
    public void getSession() {
        RequestUtils
                .get()
                .url("/api/user/session")
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        userInfoSession(null);
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        UserInfo userInfo = RequestUtils.getGson().fromJson(dataJson, UserInfo.class);
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, dataJson);
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile, userInfo.getMobile());
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord, userInfo.isHasSafeWord());
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.KYC_STATUS, userInfo.getKycStatus());
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin, userInfo.isLogin());
                        userInfoSession(userInfo);
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        userInfoSession(null);
                    }
                });
    }

    public void userInfoSession(UserInfo userInfo) {

    }


    protected void share(String content) {
        Intent share_intent = new Intent();
        share_intent.setAction(Intent.ACTION_SEND);
        share_intent.setType("text/plain");
        share_intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        share_intent.putExtra(Intent.EXTRA_TEXT, "推荐您使用一款软件:" + content);
        share_intent = Intent.createChooser(share_intent, "分享");
        startActivity(share_intent);
    }

    @Override
    public void onStart() {
        super.onStart();
        try {
            super.onStart();
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //LogUtlis.e("---------onDestroy----------");
        EventBus.getDefault().unregister(this);
        AppManager.getInstance().removeActivity(this);
    }


    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();

    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void backEvent(Object o) {
        EventBus.getDefault().removeStickyEvent(o);
    }

}
